<?php

namespace app\common;

use app\service\AesService;
use app\service\HomeService;
use support\Response;
use think\Model;

class ApiBase
{
    protected Model  $model;
    protected array  $params;
    protected string $order_sort;
    public string    $env             = '';
    public string    $controller_name = '';
    public string    $action_name     = '';

    public function beforeAction()
    {
        $this->env           = ENVIRONMENT;
//        $static_version        = $this->env == 'PRO' ? '1.01' : time();
        $controllerClass       = request()->controller;
        $this->controller_name = substr($controllerClass, strrpos($controllerClass, '\\') + 1);
        $this->action_name     = request()->action;
//        View::assign(compact('static_version'));
    }

    /**
     * 检测AES-KEY
     *
     * @return string|bool
     */
    public function checkAesTime(): string|bool
    {
        $request = \request();
        $key     = $request->post('aes_key', '');
        if (empty($key)) return 'empty aes_key';
        $key    = urlencode($key);
        $de_key = AesService::instance()->setkey(API_AES_KEY)->decrypt($key);
        if (empty($de_key)) return 'invalid key';
        $de_key_array = explode($request->action, $de_key);
        if (!isset($de_key_array[1])) return '验证信息失败，请重新获取';
        if (time() - $de_key_array[1] > 60) return '验证已过有效期，请重新获取';
        return true;
    }

    /**
     * admin接口统一获取where参数
     *
     * @return array
     */
    public function buildTableParams($osType = 0): array
    {
        $request    = \request();
        $post       = $request->post();
        $page       = $post['page'] ?? 1;
        $limit      = $post['limit'] ?? 15;
        $eq_array   = ['id', 'admin_uid', 'user_id', 'status', 'type', 'tag_id', 'item_id', 'item_type', 'stars_number', 'is_hot', 'is_recommend'];
        $time_array = ['create_time', 'u_time', 'date_v', 'pay_time', 'refund_time', 'sz_time'];
        $where[]    = ['id', '>', 0];

        foreach ($post as $key => $value) {
            if (empty($value)) continue;
            //去除sys
            if ($key == 'sys') continue;

            if (in_array($key, ['uuid', 'page', 'limit', 'admin_os_type'])) continue;
            if (is_array($value) && !in_array($key, $time_array)) {
                $where[] = [$key, 'IN', $value];
            } else {
                $where[] = match (true) {
                    in_array($key, $eq_array) => [$key, '=', $value],
                    in_array($key, $time_array) => [$key, 'BETWEEN', [explode(' - ', $value)[0] ?? myDate(), explode(' - ', $value)[1] ?? myDate()]],
                    default => [$key, 'LIKE', "%{$value}%"],
                };
            }
        }

        $this->params = [$page, $limit, $where];
        return $this->params;
    }

    public function apiSuccess($data = '', string $msg = 'success', int $code = 0): Response
    {
//        return json(['code' => $code ?: ApiStatus::API_SUCCESS->value, 'msg' => $msg, 'data' => $data, 'environment' => ENVIRONMENT == 'DEV' ? '测试环境' : ''], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
        return json(['code' => $code ?: ApiStatus::API_SUCCESS->value, 'msg' => $msg, 'data' => $data, 'environment' => ENVIRONMENT == 'DEV' ? '测试环境' : '', 'system_time' => time()]);
    }

    public function apiFailed(string $msg = 'error', int $code = 0): Response
    {
        return json(['code' => $code ?: ApiStatus::API_ERROR->value, 'msg' => $msg, 'environment' => ENVIRONMENT == 'DEV' ? '测试环境' : '', 'system_time' => time()], JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE);
    }

    public function tpl(array $assign = [], string $template = ''): Response
    {
        if (empty($template)) $template = strtolower($this->controller_name) . "/{$this->action_name}";
        return view($template, $assign);
    }
}
